<template>
  <div class="warehouse-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="sreach" class="search-form">
        <el-form-item label="仓库编码">
          <el-input v-model="sreach.warehouseCode" placeholder="请输入仓库编码" clearable />
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-input v-model="sreach.warehouseName" placeholder="请输入仓库名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="funShow">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">仓库列表</span>
          <el-button type="primary" @click="OpenAdd">
            <el-icon><Plus /></el-icon>新增仓库
          </el-button>
        </div>
      </template>

      <el-table 
        :data="tableData" 
        border 
        stripe
        highlight-current-row
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="warehouseCode" label="仓库编号" min-width="100" />
        <el-table-column prop="warehouseName" label="仓库名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="position" label="位置" min-width="120" show-overflow-tooltip />
        <el-table-column prop="area" label="面积" min-width="100">
          <template #default="scope">
            {{ scope.row.area }} m²
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="负责人" min-width="120" />
        <el-table-column prop="descs" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="success" link @click="handleArea(scope.row.warehouseCode)">
              <el-icon><HomeFilled /></el-icon>库区
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :total="page.totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 添加/编辑仓库设置 --> 
    <el-dialog 
      v-model="dialogFormVisible" 
      :title="form.id ? '编辑仓库' : '新增仓库'" 
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="warehouse-form"
        :status-icon="true"
      >
        <el-form-item label="仓库编号" prop="warehouseCode">
          <div class="code-input-group">
            <el-input 
              v-model="form.warehouseCode" 
              placeholder="请输入仓库编号" 
              :disabled="form.id !== 0 || autoGenerate"
            />
            <el-switch
              v-model="autoGenerate"
              :disabled="form.id !== 0"
              active-text="自动生成"
              class="auto-switch"
              style="width: 200px;"
              @change="handleAutoGenerateChange"
            />
          </div>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" clearable />
        </el-form-item>
        <el-form-item label="位置" prop="position">
          <el-input v-model="form.position" placeholder="请输入仓库位置" clearable>
            <template #prefix>
              <el-icon><Location /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="面积" prop="area">
          <el-input-number 
            v-model="form.area" 
            :min="0" 
            :max="10000" 
            :precision="2" 
            :step="100"
            style="width: 100%"
          >
            <template #suffix>m²</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人姓名" clearable>
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            type="textarea" 
            v-model="form.descs" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Grid, Location, User,HomeFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import http from '@/api/http'
import { useRouter } from 'vue-router'
const router = useRouter()

// 加载状态
const loading = ref(false)

// 查询条件
const sreach = reactive({
  warehouseCode: '',
  warehouseName: '',
})

// 分页条件
const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPage: 0
})

// 表单校验规则
const rules = {
  warehouseCode: [{ required: true, message: '请输入仓库编号', trigger: 'blur' }],
  warehouseName: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  position: [{ required: true, message: '请输入仓库位置', trigger: 'blur' }],
  area: [{ required: true, message: '请输入仓库面积', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
}

// 表单参数
const form = reactive({
  id: 0,
  warehouseCode: '',
  warehouseName: '',
  position: '',
  area: 0,
  leader: '',
  descs: '',
  warehouseImg:' '
})

// 表单ref
const formRef = ref()

// 仓库设置信息显示
const tableData = ref([])

// 添加自动生成开关状态
const autoGenerate = ref(false)

// 处理自动生成开关变化
const handleAutoGenerateChange = (val: boolean) => {
  if (val) {
    // 自动生成仓库编号
    const timestamp = new Date().getTime()
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    form.warehouseCode = `WH${timestamp.toString().slice(-6)}${random}`
  } else {
    form.warehouseCode = ''
  }
}

// 仓库设置信息显示
const funShow = async () => {
  try {
    loading.value = true
    const res = await axios.get('http://localhost:9991/api/WarehouseManagement/GetWarehousePageList', {
      params: {
        pageIndex: page.pageIndex,
        pageSize: page.pageSize,
        warehouseCode: sreach.warehouseCode,
        warehouseName: sreach.warehouseName,
      }
    })
    tableData.value = res.data.data
    page.totalCount = res.data.totalCount
    page.totalPage = res.data.totalPages
  } catch (error: any) {
    ElMessage.error('获取数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(sreach, {
    warehouseCode: '',
    warehouseName: '',
  })
  funShow()
}

// 打开新增弹窗
const dialogFormVisible = ref(false)
const OpenAdd = () => {
  dialogFormVisible.value = true
  autoGenerate.value = false
  Object.assign(form, {
    id: 0,
    warehouseCode: '',
    warehouseName: '',
    position: '',
    area: 0,
    leader: '',
    descs: '',
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      funAdd()
    }
  })
}

// 新增/编辑
const funAdd = async () => {
  try {
    loading.value = true
    const url = form.id 
      ? 'api/WarehouseManagement/UpdateWarehouse'
      : 'api/WarehouseManagement/CreateWarehouse'
    
    await http.post(url, form)
    ElMessage.success(form.id ? '更新成功' : '新增成功')
    dialogFormVisible.value = false
    funShow()
  } catch (error: any) {
    ElMessage.error((form.id ? '更新' : '新增') + '失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 编辑仓库
const handleEdit = (row: any) => {
  Object.assign(form, row)
  dialogFormVisible.value = true
}

// 删除仓库
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该仓库?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      loading.value = true
      await http.post('api/WarehouseManagement/DeleteWarehouse', row)
      ElMessage.success('删除成功')
      funShow()
    } catch (error: any) {
      ElMessage.error('删除失败：' + error.message)
    } finally {
      loading.value = false
    }
  })
}

// 查看库区
const handleArea = (warehouseCode: any) => {
  // TODO: 实现库区管理功能
  router.push({
    path: '/reservoirarea',
    query: {
      warehouseCode: warehouseCode
    }
  })
}

// 监听分页变化
watch(page, () => {
  funShow()
})

// 初始化
onMounted(() => {
  funShow()
})
</script>

<style scoped>
.warehouse-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.header-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #409eff;
  border-radius: 2px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
}

.warehouse-form {
  padding: 24px 16px;
}

.dialog-footer {
  text-align: right;
  padding: 16px 0 0;
  border-top: 1px solid #ebeef5;
  margin-top: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #303133;
  font-weight: 500;
  height: 48px;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-button) {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

.code-input-group {
  display: flex;
  align-items: center;
  gap: 16px;
}

.auto-switch {
  min-width: 100px;
}

:deep(.el-switch__label) {
  color: #606266;
  font-size: 13px;
}
</style>
